package cn.kgc.util.resultutil;

import cn.kgc.util.resultutil.exception.HttpException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YC
 * 封装控制器方法的返回值信息
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 返回数据
     */
    private T data;
    /**
     * 返回信息
     */
    private String message;

    /**
     * 请求成功无数据的封装
     *
     * @return Result对象
     */
    public static Result<Object> success() {
        return Result.builder()
                .code(ResultConstant.SUCCESS.getCode())
                .message(ResultConstant.SUCCESS.getMessage()).build();
    }

    /**
     * 请求成功有数据的封装
     *
     * @param data 返回数据
     * @return Result对象
     */
    public static Result<Object> success(Object data) {
        return Result.builder()
                .code(ResultConstant.SUCCESS.getCode())
                .message(ResultConstant.SUCCESS.getMessage())
                .data(data).build();
    }

    /**
     * 运行时异常的封装
     *
     * @param httpException 自定义异常
     * @return Result对象
     */
    public static Result<Object> error(HttpException httpException) {
        return Result.builder()
                .code(httpException.getCode())
                .message(httpException.getMessage()).build();
    }

    /**
     * 检查异常无数据的封装
     *
     * @param exception 其他异常（检查异常）
     * @return Result对象
     */
    public static Result<Object> error(Exception exception) {
        return error(exception, null);
    }

    /**
     * 检查异常有数据的封装
     *
     * @param exception 其他异常
     * @param data      返回的数据
     * @return Result对象
     */
    public static Result<Object> error(Exception exception, Object data) {
        return Result.builder()
                .code(ResultConstant.ERROR.getCode())
                .message(ResultConstant.ERROR.getMessage())
                .data(data).build();
    }

    /**
     * 对象参数验证失败的封装
     *
     * @param exception 异常
     * @return Result对象
     */
    public static Result<Object> instanceVerifyFail(MethodArgumentNotValidException exception) {
        // 获取异常绑定结果
        BindingResult result = exception.getBindingResult();
        // 获取字段错误列表
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String, String> map = new HashMap<>(fieldErrors.size());
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Result.builder()
                .code(ResultConstant.VERIFY_ERROR.getCode())
                .message(ResultConstant.VERIFY_ERROR.getMessage() + map)
                .data(null).build();
    }

    /**
     * 普通（单个/多个）参数验证失败的封装
     *
     * @param exception 异常
     * @return Result对象
     */
    public static Result<Object> commonVerifyFail(ConstraintViolationException exception) {
        System.out.println(exception.getMessage());
        String[] split = exception.getMessage().split(",");
        Map<String, String> map = new HashMap<>(split.length + 1);
        for (String s : split) {
            String[] split2 = s.split(": ");
            map.put(split2[0].split("\\.")[1], split2[1]);
        }
        return Result.builder()
                .code(ResultConstant.VERIFY_ERROR.getCode())
                .message(ResultConstant.VERIFY_ERROR.getMessage() + map)
                .data(null).build();
    }
}
